<template>
  <div class="up_box">
    <div class="pdfView" v-show="PdfPreviewFlag" @click.stop>
      <van-icon name="close" @click="closePdfPreview" class="close" />
      <PdfPreview :url="PdfUrl" v-if="PdfUrl" :id="PdfUrl" />
    </div>
    <template v-if="albumList.length < limitNum && entry">
      <van-button class="up_btn" type="info" v-if="selfBtn && selfWord" size="small" @click="uploadAnnex">
        {{ selfWord }}
      </van-button>
      <div class="up_li" v-else-if="selfBtn && !selfWord">
        <van-icon name="plus" class="icon" />
      </div>
      <div class="up_li_sugAnnex" v-else @click="uploadAnnex">
        <span class="text">{{ btnName }}</span>
      </div>
      <input
        type="file"
        ref="fileInput"
        class="file-input"
        :accept="accept"
        :multiple="isMultiple"
        @change="onFileChange" />
    </template>
    <!-- <van-uploader
      :after-read="openUpload1"
      result-type="file"
      multiple
      :accept="accept"
      v-if="albumList.length !== 9 && entry">
      <van-button class="up_btn" type="info" v-if="selfBtn && selfWord" size="small">{{ selfWord }}</van-button>
      <div class="up_li" v-else-if="selfBtn && !selfWord">
        <van-icon name="plus" class="icon" />
      </div>
      <div class="up_li_sugAnnex" v-else>
        <span class="text">{{ btnName }}</span>
      </div>
    </van-uploader> -->
    <!-- 图片列表 -->
    <template v-if="showImg">
      <div class="up_file_li" :class="{ is_list: selfBtn && !selfWord }" v-if="imglist.length > 0">
        <PicturePreview :albumList="imglist" :entry="entry" @deleteImg="deleteImg" :showBig="showBig" />
      </div>
    </template>
    <!-- 文件列表 -->
    <template v-if="showList">
      <div class="up_file_li" v-for="(item, index) in filelist" :key="'file' + index">
        <span class="iconfont iconicon-test"></span>
        <div class="text">{{ item.name }}</div>
        <div class="preview" @click="previewFile(item, 'file')" v-show="showPreBtn(item)">
          <van-icon name="eye-o" size="18" color="#0f61d5" />
          预览
        </div>
        <div class="close" @click="deleteFile(item, 'file')" v-if="entry">
          <van-icon name="delete-o" size="18" color="#0f61d5" />
          删除
        </div>
      </div>
    </template>
  </div>
</template>

<script>
import PicturePreview from '@com/PicturePreviewImg'
import PdfPreview from '@com/PdfView'
import { uploadFiles } from '@api/api.js'
import { popstateHandler } from '@/common/popstateHandler.js'
import { getFileTypeByName } from '@/common/utility'
export default {
  name: 'ImgUploadImg',
  components: {
    PicturePreview,
    PdfPreview,
  },
  props: {
    albumList: {
      type: Array,
      default: () => {
        return []
      },
    },
    entry: {
      type: Boolean,
      default: true,
    },
    selfBtn: {
      type: Boolean,
      default: false,
    },
    showImg: {
      type: Boolean,
      default: true,
    },
    showList: {
      type: Boolean,
      default: true,
    },
    selfWord: {
      type: String,
      default: '',
    },
    showBig: {
      type: Boolean,
      default: false,
    },
    accept: {
      type: String,
      default:
        '.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.jpeg,.png,.jpg,.mp3,.mp4,.rmvb,.mkv,.avi,.mov,.zip,.rar,.7z,.gz,',
    },
    btnName: {
      type: String,
      default: '上传附件',
    },
    limitNum: {
      type: Number,
      default: 9,
    },
    isMultiple: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      fileIcon: require('./../assets/images/common/file.png'),
      imglist: [],
      filelist: [],
      imgArr: [],
      PdfPreviewFlag: false,
      PdfUrl: '',
      docStyleList: ['xlsx', 'xls', 'doc', 'docx', 'pdf', 'txt'],
      previewShow: false,
    }
  },
  computed: {},
  watch: {
    albumList() {
      if (this.albumList.length > 0) {
        const albumListArr = this.albumList
        this.imglist = []
        this.filelist = []
        albumListArr.forEach(el => {
          if (['jpeg', 'png', 'jpg', 'mp4', 'mov'].includes(el.fileType.toLowerCase())) {
            this.imglist.push(el)
          } else {
            this.filelist.push(el)
          }
        })
      } else {
        this.imglist = []
        this.filelist = []
      }
    },
    previewShow(now) {
      if (now) {
        // 有附件展示的时候屏蔽物理返回键
        // history.pushState(null, null, location.href)
        const that = this
        popstateHandler.popstateListener(() => {
          that.closePdfPreview()
        }, 'previewShow')
      } else {
        popstateHandler.removePopstateListener('previewShow')
      }
    },
  },
  created() {},
  mounted() {
    if (this.albumList.length > 0) {
      const albumListArr = this.albumList
      this.imglist = []
      this.filelist = []
      albumListArr.forEach(el => {
        if (['jpeg', 'png', 'jpg', 'mp4', 'mov'].includes(el.fileType.toLowerCase())) {
          this.imglist.push(el)
        } else {
          this.filelist.push(el)
        }
      })
    }
  },
  methods: {
    openUpload1(file) {
      let fileFlag = true
      if (file.constructor === Array) {
        for (let i = 0; i < file.length; i++) {
          const name = file[i].file.name
          const suffix = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
          if (this.accept.indexOf(suffix) === -1) {
            this.$toast.fail('请上传允许的文件类型')
            fileFlag = false
            break
          }
        }
      } else {
        const name = file.file.name
        const suffix = name.substring(name.lastIndexOf('.') + 1).toLowerCase()
        if (this.accept.indexOf(suffix) === -1) {
          this.$toast.fail('请上传允许的文件类型')
          fileFlag = false
        }
      }
      if (fileFlag) {
        this.openUpload(file)
      }
    },
    // 图片/视频
    openUpload(file, detail) {
      const that = this
      // 此时可以自行将文件上传至服务器
      const formData = new FormData()
      if (file instanceof Array) {
        if (file.length + that.albumList.length > 9) {
          this.$toast.fail('最多只能上传9个')
          return false
        }
        file.forEach(li => {
          formData.append('files', li.file)
        })
      } else {
        if (that.albumList.length === 9) {
          this.$toast.fail('最多只能上传9个')
          return false
        }
        formData.append('files', file.file)
      }
      uploadFiles(formData).then(res => {
        const resData = res.data
        resData.forEach(el => {
          if (['jpeg', 'png', 'jpg', 'mp4', 'mov'].includes(el.fileType.toLowerCase())) {
            that.imglist.push(el)
          } else {
            that.filelist.push(el)
          }
        })
        that.albumList.push(...resData)
        that.$emit('temporaryStorage')
      })
    },
    // 图片视频删除
    deleteImg() {
      const allFile = this.imglist.concat(this.filelist)
      this.$emit('update:albumList', allFile)
      this.$emit('temporaryStorage')
      this.$emit('edit', allFile)
    },
    deleteFile(li, style) {
      // console.log(li);
      this.$dialog
        .confirm({
          message: '确定要删除附件？',
        })
        .then(() => {
          if (style === 'img') {
            this.imglist.splice(
              this.imglist.findIndex(item => item.id === li.id),
              1
            )
            this.deleteImg()
          } else if (style === 'file') {
            this.filelist.splice(
              this.filelist.findIndex(item => item.id === li.id),
              1
            )
            this.deleteImg()
          }
        })
        .catch(() => {})
    },
    // 关闭文件预览
    closePdfPreview() {
      this.PdfPreviewFlag = false
      this.PdfUrl = ''
      this.previewShow = false
    },
    // 文件预览按钮是否展示
    showPreBtn(item) {
      if (this.docStyleList.indexOf(item.fileType.toLowerCase()) !== -1) {
        return true
      } else {
        return false
      }
    },
    // 预览
    previewFile(item, style) {
      const that = this
      that.previewShow = true
      that.$emit('changeAlive')
      if (style === 'file') {
        if (item.fileType === 'pdf') {
          that.PdfUrl = item.sourcePath
        } else {
          that.PdfUrl = item.thumbnailPath
        }
        that.PdfPreviewFlag = true
      }
    },
    uploadAnnex() {
      if (this.entry) {
        this.$refs.fileInput.click()
      }
    },
    onFileChange(e) {
      const files = e.target.files
      console.log('files...', files.length)
      let invalid = false // 判断文件类型
      let insize = 0 // 判断文件大小

      // 判断是否符合文件类型限制
      for (const item of files) {
        if (!this.accept.includes(getFileTypeByName(item.name))) {
          invalid = true
          break
        }
        console.log('item :>> ', item)
        insize += item.size / 1024 / 1024
      }
      if (invalid) {
        this.$toast.fail('请选择指定的文件类型！')
        this.resetFileSelect()
        return
      }
      if (insize >= 20) {
        this.$toast.fail('单次上传附件大小总和限制在20M以内')
        this.resetFileSelect()
        return
      }

      // 判断是否超出限制
      if (this.albumList.length + files.length > this.limitNum) {
        this.$toast.fail(`最多只能上传${this.limitNum}个文件！`)
        this.resetFileSelect()
        return
      }

      const list = [...files]
      this.$refs.fileInput.value = null
      // 调用上传接口
      this.callUploadRequest(list)
    },
    resetFileSelect() {
      this.$refs.fileInput.value = null
    },
    callUploadRequest(files) {
      const formData = new FormData()
      files.forEach(item => {
        formData.append('files', item)
      })
      uploadFiles(formData).then(res => {
        const resData = res.data
        resData.forEach(el => {
          if (['jpeg', 'png', 'jpg', 'mp4', 'mov'].includes(el.fileType.toLowerCase())) {
            this.imglist.push(el)
          } else {
            this.filelist.push(el)
          }
        })
        this.albumList.push(...resData)
        this.$emit('temporaryStorage', files)
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.up_box {
  display: flex;
  flex-wrap: wrap;
  padding: 8px;
  .pdfView {
    width: 375px;
    height: 100vh;
    background: rgba($color: #fff, $alpha: 1);
    position: absolute;
    top: 0;
    left: 50%;
    transform: translate(-50%);
    z-index: 999;
    .close {
      position: absolute;
      top: 35px;
      right: 25px;
      width: 25px;
      z-index: 1000;
    }
  }
  @include ellipsis;
  /deep/.up_li {
    width: 90px;
    height: 90px;
    background-color: #f8f8f8;
    border-radius: 1px;
    position: relative;
    margin-bottom: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    color: #999999;
    font-size: 12px;
    .icon {
      font-size: 20px;
      color: #666666;
    }
    .text {
      font-size: 12px;
    }
  }
  /deep/.up_li_sugAnnex {
    font-size: 14px;
    color: #0f61d5;
    .text {
      margin-left: 10px;
    }
    .iconicon-test {
      font-size: 12px;
    }
  }
  .up_file_li {
    width: 100%;
    color: #0f61d5;
    margin-top: 5px;
    // margin-bottom: 5px;
    display: flex;
    align-items: center;
    .iconicon-test {
      font-size: 12px;
    }
    .text {
      font-size: 13px;
      margin: 0 10px;
      line-height: 20px;
      flex: 1;
      width: 0;
      @include ellipsis;
    }
    .preview {
      font-size: 13px;
      margin: 0 10px;
      display: flex;
      align-items: center;
    }
    .close {
      font-size: 13px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .up_file_li_btn {
    width: 100%;
    color: #0f61d5;
    margin-bottom: 10px;
    display: flex;
    .text {
      font-size: 13px;
    }
  }
  /deep/.is_list {
    .previews::after {
      content: '';
      width: 30%;
    }
    .up_li {
      width: 30% !important;
    }
  }
  .file-input {
    display: none;
  }
}
</style>
